#include <QVector3D>
#include <QMatrix4x4>

#include "minecraftalgorthm.h"
#include "minecraftblock.h"

MineCraftBlockGeometry::MineCraftBlockGeometry()
{

}

void MineCraftBlockGeometry::rebuild()
{
    clear();

    int stride = 3 * sizeof(float) + 2 * sizeof(float);
    QByteArray vertexData;

    do
    {
        if(m_type == BlockMeta::None)
        {
            break;
        }

        auto meta = MineCraftBlockLibrary::instance()->getBlock(m_type);
        if(!meta)
        {
            break;
        }

        auto attri = meta->attribute();

        if(attri & BlockMeta::BlockShape)
        {
            MineCraftAlgorthm::genMineCraftBlock(vertexData,{0,0,0},meta->faces());
        }
        else
        {
            MineCraftAlgorthm::createMeshBlock(vertexData,meta->mesh(),{});
        }

    }while(false);

    setVertexData(vertexData);
    setStride(stride);
    setBounds(QVector3D(-50,-50,-50),QVector3D(50,50,50));
    setPrimitiveType(QQuick3DGeometry::PrimitiveType::Triangles);
    addAttribute(QQuick3DGeometry::Attribute::PositionSemantic,0,QQuick3DGeometry::Attribute::F32Type);
    addAttribute(QQuick3DGeometry::Attribute::TexCoordSemantic,3 * sizeof(float),QQuick3DGeometry::Attribute::F32Type);
}

BlockMeta::BlockType MineCraftBlockGeometry::type() const
{
    return m_type;
}

void MineCraftBlockGeometry::setType(const BlockMeta::BlockType &newType)
{
    if (m_type == newType)
        return;
    m_type = newType;
    emit typeChanged();
    rebuild();
}

